/**
 * 项目名称：最简单的LED驱动程序
 * 单片机：STC8G1K08
 * 频率：12Mhz
 * PCB:1603120A_Y3
 * 学习目标：通过配置定时器2看懂手册上关于寄存器的内容
   */

#include "stc8g.h" //加载此头文件以后不需要再加载reg51.h

#define LED_0 P35
#define LED_1 P34
#define LED_2 P10
#define LED_3 P11
#define LED_4 P16
#define LED_5 P17
#define LED_6 P54
#define LED_7 P55

unsigned char ledState; //led状态
volatile unsigned char timer2_t = 20; //1000 / 50 = 20

//软件延时
void Delay500ms() {
    unsigned char i, j, k;

    i = 29;
    j = 14;
    k = 54;
    do {
        do {
            while (--k);
        } while (--j);
    } while (--i);
}

//刷新LED状态
void led_update_display() {
    LED_0 = ledState & (0x01 << 0);
    LED_1 = ledState & (0x01 << 1);
    LED_2 = ledState & (0x01 << 2);
    LED_3 = ledState & (0x01 << 3);
    LED_4 = ledState & (0x01 << 4);
    LED_5 = ledState & (0x01 << 5);
    LED_6 = ledState & (0x01 << 6);
    LED_7 = ledState & (0x01 << 7);
}

//初始化IO
void pin_init() {
    P1M1 = 0x00;
    P1M0 = (0x01 << 7) | (0x01 << 6) | (0x01 << 1) | (0x01 << 0);

    P3M1 = 0x00;
    P3M0 = (0x01 << 5) | (0x01 << 4);

    P5M1 = 0x00;
    P5M0 = (0x01 << 5) | (0x01 << 4);
}

//定时器2 初始化 50ms@12Mhz
void timer2_init(){
    AUXR &= 0xFB;       //定时器时钟12T模式 1111 1011
    T2L = 0xB0;     //设置定时初值
    T2H = 0x3C;     //设置定时初值
    AUXR |= 0x10;       //定时器2开始计时
}


void main() {
    
    pin_init();
    timer2_init();
    ledState = 0x00;
    led_update_display(); //关闭所有LED

    IE2 |= 0x04; //ET2 置1 使能(允许)定时器2中断
    EA = 1; //使能总中断 (打开中断总开关)
    while(1) {
    }
}


//定时器2 中断函数
void time2_ISR() interrupt 12{
    if(--timer2_t == 0){
        timer2_t = 20;
        LED_0 = !LED_0;
    }
    
    AUXINTIF &= 0xFE; //清除定时器2的中断标志 T2IF位置0
} 